package icu.zlz.emqx.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import icu.zlz.common.core.exception.ServiceException;
import icu.zlz.common.core.utils.DateUtils;
import icu.zlz.common.core.utils.uuid.IdUtils;
import icu.zlz.common.core.web.domain.AjaxResult;
import icu.zlz.common.security.utils.SecurityUtils;
import icu.zlz.emqx.domain.IotDevices;
import icu.zlz.emqx.domain.IotGroup;
import icu.zlz.emqx.domain.MqttUserOnline;
import icu.zlz.emqx.mapper.IotDevicesMapper;
import icu.zlz.emqx.mapper.IotDevicesTopicMapper;
import icu.zlz.emqx.mapper.IotGroupMapper;
import icu.zlz.emqx.mapper.IotTopicMapper;
import icu.zlz.emqx.service.IIotDevicesService;
import icu.zlz.emqx.service.IIotDevicesTopicService;
import icu.zlz.emqx.service.IIotGroupService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 设备管理Service业务层处理
 *
 * @author zangs
 * @since 2025-01-02
 */
@Service
public class IotDevicesServiceImpl implements IIotDevicesService {
    @Resource
    private IotDevicesMapper iotDevicesMapper;
    @Resource
    private IotDevicesTopicMapper iotDevicesTopicMapper;
    @Resource
    private IotGroupMapper iotGroupMapper;
    @Resource
    private IotTopicMapper iotTopicMapper;
    @Resource
    private MqttAuthService mqttAuthService;
    @Resource
    private IIotGroupService iotGroupService;
    @Resource
    private IIotDevicesTopicService iIotDevicesTopicService;

    /**
     * 查询设备管理
     *
     * @param deviceId 设备管理主键
     * @return 设备管理
     */
    @Override
    public IotDevices selectIotDevicesByDeviceId(Long deviceId) {
        IotDevices iotDevices = iotDevicesMapper.selectIotDevicesByDeviceId(deviceId);
        iotDevices.setIotDevicesTopicList(iIotDevicesTopicService.selectIotDevicesTopicByDeviceId(iotDevices.getDeviceId()));
        return iotDevices;
    }

    @Override
    public List<IotDevices> selectIotDevicesByDeviceIds(Long[] deviceIds) {
        return iotDevicesMapper.selectIotDevicesByDeviceIds(deviceIds);
    }

    /**
     * 查询设备管理列表
     *
     * @param iotDevices 设备管理
     * @return 设备管理
     */
    @Override
    public List<IotDevices> selectIotDevicesList(IotDevices iotDevices) {
        return iotDevicesMapper.selectIotDevicesList(iotDevices);
    }

    /**
     * 新增设备管理
     *
     * @param iotDevices 设备管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertIotDevices(IotDevices iotDevices) {
        IotGroup iotGroup = iotGroupService.getIotGroupByGroupId(iotDevices.getGroupId());


        if (!ObjectUtils.isEmpty(iotGroup)) {
            iotDevices.setUid(IdUtils.simpleUUID());
            iotDevices.setCreateBy(SecurityUtils.getUsername());
            iotDevices.setCreateTime(DateUtils.getNowDate());
            int i = iotDevicesMapper.insertIotDevices(iotDevices);
            iIotDevicesTopicService.batchContacts(iotGroup, iotDevices);

            MqttUserOnline mqttUserOnline = new MqttUserOnline();
            mqttUserOnline.setOnline(false);
            mqttUserOnline.setClientId(iotDevices.getDeviceClientId());
            mqttUserOnline.setDeviceUid(iotDevices.getUid());
            mqttUserOnline.setUserUid(iotGroup.getUid());
            AjaxResult ajaxResult = mqttAuthService.addUserStatus(Collections.singletonList(mqttUserOnline));
            if (!ajaxResult.isSuccess()) {
                throw new ServiceException("添加在线记录表失败" + ajaxResult.get(AjaxResult.MSG_TAG));
            }
            return i;
        }


        return 0;
    }

    /**
     * 修改设备管理
     *
     * @param iotDevices 设备管理
     * @return 结果
     */
    @Transactional
    @Override
    public int updateIotDevices(IotDevices iotDevices) {
        IotGroup iotGroup = iotGroupService.getIotGroupByGroupId(iotDevices.getGroupId());

        if (!ObjectUtils.isEmpty(iotGroup)) {
            IotDevices old = iotDevicesMapper.selectIotDevicesByDeviceId(iotDevices.getDeviceId());

            iotDevices.setUid(null);
            iotDevices.setGroupId(null);
            iotDevices.setUpdateBy(SecurityUtils.getUsername());
            iotDevices.setUpdateTime(DateUtils.getNowDate());
            int i = iotDevicesMapper.updateIotDevices(iotDevices);
            iIotDevicesTopicService.batchContacts(iotGroup, iotDevices);


            if (!ObjectUtils.isEmpty(old) && !old.getDeviceClientId().equals(iotDevices.getDeviceClientId())) {
                MqttUserOnline mqttUserOnline = new MqttUserOnline();
                mqttUserOnline.setDeviceUid(old.getUid());
                mqttUserOnline.setClientId(iotDevices.getDeviceClientId());


                AjaxResult ajaxResult = mqttAuthService.editUserStatus(Collections.singletonList(mqttUserOnline));
                if (!ajaxResult.isSuccess()) {
                    throw new ServiceException("修改客户端Id失败" + ajaxResult.get(AjaxResult.MSG_TAG));
                }
            }

            return i;
        }
        return 0;
    }


    /**
     * 批量删除设备管理
     *
     * @param deviceIds 需要删除的设备管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteIotDevicesByDeviceIds(Long[] deviceIds) {
        iotDevicesTopicMapper.deleteIotDevicesTopicByDevicesIds(deviceIds);

        return iotDevicesMapper.deleteIotDevicesByDeviceIds(deviceIds);
    }

    /**
     * 删除设备管理信息
     *
     * @param deviceId 设备管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteIotDevicesByDeviceId(Long deviceId) {
        iotDevicesTopicMapper.deleteIotDevicesTopicByDevicesIds(new Long[]{deviceId});

        return iotDevicesMapper.deleteIotDevicesByDeviceId(deviceId);
    }

    @Override
    public List<Map<String, Object>> selectIotGroupList(String name) {
        if (SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            iotGroupMapper.selectIotGroupMapList(name, null);
        }
        return iotGroupMapper.selectIotGroupMapList(name, SecurityUtils.getUserId());
    }

    @Override
    public List<Map<String, Object>> selectIotTopicList() {
        if (SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            iotTopicMapper.selectIotTopicMapList(null);
        }
        return iotTopicMapper.selectIotTopicMapList(SecurityUtils.getUserId());
    }


    @Override
    public Map getOnlineClients(AjaxResult clients) {
        if (clients.isSuccess()) {
            ObjectMapper objectMapper = new ObjectMapper();
            String data = (String) clients.get(AjaxResult.DATA_TAG);
            try {
                Map map = objectMapper.readValue(data, Map.class);

                System.out.println(map);
                return map;
            } catch (IOException e) {
                throw new ServiceException(e.getMessage());
            }
        }
        return null;
    }


}
